package com.ruoyi.project.weixin.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.weixin.mp.entity.WxQrCode;
import com.ruoyi.project.weixin.mp.form.WxQrCodeForm;
import com.ruoyi.project.weixin.mp.service.WxQrCodeService;
import com.ruoyi.project.weixin.mp.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 * 公众号带参二维码管理
 * https://github.com/Wechat-Group/WxJava/wiki/MP_二维码管理
 */
@RestController
@RequestMapping("/manage/wxQrCode")
@Api(tags = {"公众号带参二维码-管理后台"})
public class WxQrCodeManageController {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxQrCodeService wxQrCodeService;

    @Autowired
    private WxMpService wxMpService;

    /**
     * 创建带参二维码ticket
     */
    @PostMapping("/createTicket")
    @PreAuthorize("@ss.hasPermi('wx:wxqrcode:save')")
    @ApiOperation(value = "创建带参二维码ticket",notes = "ticket可以换取二维码图片")
    public AjaxResult createTicket(@RequestBody JSONObject jsonObject) throws WxErrorException {
        String appid = jsonObject.getString("appid");
        wxMpService.switchoverTo(appid);
        WxQrCodeForm form = jsonObject.getObject("form", WxQrCodeForm.class);
        WxMpQrCodeTicket ticket = wxQrCodeService.createQrCode(appid,form);
        return AjaxResult.success(ticket);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('wx:wxqrcode:list')")
    @ApiOperation(value = "列表")
    public AjaxResult list(@RequestParam Map<String, Object> params) {
        PageUtils page = wxQrCodeService.queryPage(params);
        return AjaxResult.success(page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@ss.hasPermi('wx:wxqrcode:info')")
    @ApiOperation(value = "详情")
    public AjaxResult info(@CookieValue String appid,@PathVariable("id") Long id) {
        WxQrCode wxQrCode = wxQrCodeService.getById(id);
        return AjaxResult.success(wxQrCode);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPermi('wx:wxqrcode:delete')")
    @ApiOperation(value = "删除")
    public AjaxResult delete(@CookieValue String appid,@RequestBody Long[] ids) {
        wxQrCodeService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }
}